<?php

function curl($url, $fields = array(), $auth = false){

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_VERBOSE, 1);
    curl_setopt($curl, CURLOPT_HEADER, 1);

    if($auth){
        curl_setopt($curl, CURLOPT_USERPWD, "$auth");
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    }

    if(!empty($fields)){
        $fields_string = http_build_query($fields);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string);
    }

    $response = curl_exec($curl);
    $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
    //$header_string = substr($response, 0, $header_size);
    $body = substr($response, $header_size);
    curl_close($curl);
    //return array($body, $headers);
    return $body;
}


function formateCategory($data,$id='id',$pid='pid',$name="category"){
    $temp = array();
    foreach($data as $k => $v){
        if($v['pid'] == 0){
            $v['_name'] = $v[$name];
            $array = $v;
            $temp[$v['id']] = $v;
        }else{
            $v['_name'] = '|-' .$v[$name];
            $temp[$v['pid']]['son'][] = $v;
        }
    }
    return $temp;
}


function thumImg($imgPath = '', $w = null, $h = null,$savePath = null,$isWater=true)
{
    if ($imgPath != '') {

        $w = $w == null ? C('thumb_width') : $w ;
        $h = $h == null ? C('thumb_height') : $h ;
        $savePath = $savePath == null ? C('thumb_save_path') : $savePath;

        $url='http://'.$_SERVER['HTTP_HOST'] .'/';
        $imgPath = str_replace(array($url),array('.'),$imgPath);
        preg_match("/UploadFiles/",$imgPath,$matches);
        if(empty($matches))  $imgPath = C('thumb_save_path') . "{$w}_{$h}/{$imgPath}";

        $image = new \Think\Image();
        $image->open($imgPath);
        $width = $image->width(); // 返回图片的宽度
        $height = $image->height(); // 返回图片的高度
        $fileName = basename($imgPath);
        if($height < 200 || $width < 200 || $w < 200 || $h < 200) $isWater = false;
        $savePath = $savePath ."{$w}_{$h}/{$fileName}";
        $dir = dirname($savePath);
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        if ($width > $w || $height > $h) {
            if($isWater){
                $image->thumb($w, $h,\Think\Image::IMAGE_THUMB_SCALE)->water(C('thumb_water'))->save($savePath);
            }else{
                $image->thumb($w, $h,\Think\Image::IMAGE_THUMB_SCALE)->save($savePath);
            }

        } else {
            if($isWater){
                $image->water(C('thumb_water'))->save($savePath);
            }else{
                $image->save($savePath);
            }

        }
        return $savePath;
    }else{
        return null;
    }
}


/**
 * 发送邮件
 * @param string $address
 * @param string $subject
 * @param string $message
 * @return array<br>
 * 返回格式：<br>
 * array(<br>
 * 	"error"=>0|1,//0代表出错<br>
 * 	"message"=> "出错信息"<br>
 * );
 */
function send_email($address,$subject,$message){
    import("Org.Util.PHPMailer");
    $mail=new \PHPMailer();
    // 设置PHPMailer使用SMTP服务器发送Email
    $mail->IsSMTP();
    $mail->IsHTML(true);
    // 设置邮件的字符编码，若不指定，则为'UTF-8'
    $mail->CharSet='UTF-8';
    // 添加收件人地址，可以多次使用来添加多个收件人
    $mail->AddAddress($address);
    // 设置邮件正文
    $mail->Body=$message;
    // 设置邮件头的From字段。
    $mail->From= C('cfg_mail_from');
    // 设置发件人名字
    $mail->FromName= C('cfg_mail_fromname');;
    // 设置邮件标题
    $mail->Subject=$subject;
    // 设置SMTP服务器。
    $mail->Host= C('cfg_mail_host');
    // 设置SMTP服务器端口。
    $port= C('mail_smtp_port');
    $mail->Port=empty($port)?"25":$port;
    // 设置为"需要验证"
    $mail->SMTPAuth=true;
    // 设置用户名和密码。
    $mail->Username= C('cfg_mail_username');
    $mail->Password= C('cfg_mail_password');
    // 发送邮件。
    if(!$mail->Send()) {
        $mailerror=$mail->ErrorInfo;
        return array("error"=>1,"message"=>$mailerror);
    }else{
        return array("error"=>0,"message"=>"success");
    }
}


/**
 * 邮件发送函数
 */
function sendMail($to, $title, $content) {

    //Vendor('PHPMailer.PHPMailerAutoload');
    import("Org.Util.PHPMailerAutoload");
    $mail = new PHPMailer(); //实例化
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host=C('MAIL_HOST'); //smtp服务器的名称（这里以QQ邮箱为例）
    $mail->SMTPAuth = C('MAIL_SMTPAUTH'); //启用smtp认证
    $mail->Username = C('MAIL_USERNAME'); //你的邮箱名
    $mail->Password = C('MAIL_PASSWORD') ; //邮箱密码
    $mail->From = C('MAIL_FROM'); //发件人地址（也就是你的邮箱地址）
    $mail->FromName = C('MAIL_FROMNAME'); //发件人姓名
    $mail->AddAddress($to,"尊敬的客户");
    $mail->WordWrap = 50; //设置每行字符长度
    $mail->IsHTML(C('MAIL_ISHTML')); // 是否HTML格式邮件
    $mail->CharSet=C('MAIL_CHARSET'); //设置邮件编码
    $mail->Subject =$title; //邮件主题
    $mail->Body = $content; //邮件内容
    $mail->AltBody = "这是一个纯文本的身体在非营利的HTML电子邮件客户端"; //邮件正文不支持HTML的备用显示
    return($mail->Send());
}


function mergeCidPid($list){
    $cid = array_column($list,'id');
    if($list){
        $pid[0] = $list[0]['pid'];
    }else{
        $pid = array();
    }
    $cid = array_merge($cid,$pid);
    return $cid;
}


function upload($fileType=null,$isThumb=false,$path=null,$size=null,$width,$height){
    if($fileType == 'images' || $fileType == null){
        $fileType = array('jpg', 'gif', 'png', 'jpeg');
    }
    $size = $size ? $size : 3145728;
    $path = $path ? $path : 'upload';
    if($isThumb){
        $width = $width ? $width : 200;
        $height = $height ? $height : 180;
    }
    if ($_FILES) {
        $key = array_keys($_FILES)[0];
        if ($_FILES[$key]['error'] != 4) {


            //上传图像
            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize = $size;// 设置附件上传大小
            $upload->exts = $fileType;// 设置附件上传类型
            $upload->rootPath = C('UPLOAD_DIR'); // 设置附件上传根目录
            $upload->savePath = $path; // 设置附件上传（子）目录
            $upload->saveName = date('ymdHis');
            $upload->autoSub = false;
            $file = $upload->upload();

            if (!$file) {// 上传错误提示错误信息
                $path = '上传错误';
                $code = 0;
            } else {
                if($isThumb){
                    $tempPath = C('UPLOAD_DIR') . $file[$key]['savepath'] . $file[$key]['savename'];
                    $thumSavePath = thumInfoImg($tempPath, $width, $height,array($path));
                    $path = C('cfg_basehost') . substr($thumSavePath, 1);
                    $code = 1;
                }else{
                    $path = C('UPLOAD_DIR') . $file[$key]['savepath'] . $file[$key]['savename'];
                    $code = 1;
                }
            }
            $return = array(
                'code'  => $code,
                'path'  => $path
            );
            return $return;
        }
    }
}


function thumInfoImg($imgPath = '', $w = 800, $h = 800 , $savePath = null,$isWater = true)
{
    if ($imgPath != '') {
        $savePath = $savePath == null ? C('thumb_save_path') : $savePath;
        $image = new \Think\Image();
        $image->open($imgPath);
        $width = $image->width(); // 返回图片的宽度
        $height = $image->height(); // 返回图片的高度
        if($height < 200 || $width < 200 || $w < 200 || $h < 200) $isWater = false;
        $fileName = basename($imgPath);
        if(is_array($savePath)){
            $savePath = C('UPLOAD_DIR'). $savePath[0] .'/' . $fileName;
        }else{
            $savePath = C('thumb_save_path')."{$w}_{$h}/{$fileName}";
        }
        $dir = dirname($savePath);
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        if ($width > $w || $height > $h) {
            if($isWater){
                $image->crop($w, $h)->water(C('thumb_water'))->save($savePath);
            }else{
                $image->crop($w, $h)->save($savePath);
            }
        } else {
            if($isWater){
                $image->water(C('thumb_water'))->save($savePath);
            }else{
                copy($imgPath, $savePath);
            }

        }
        return $savePath;
    }else{
        return null;
    }
}


/**
 * @param $directory
 * @param bool $subdir
 * @return bool
 * @des 删除目录（包括下面的文件）
 */
function delDir($directory, $subdir = true) {
    if (is_dir($directory) == false) {
        $error = "该目录是不存在！";
        return false;
    }
    $handle = opendir($directory);
    while (($file = readdir($handle)) !== false) {
        if ($file != "." && $file != "..") {
            is_dir("$directory/$file") ?
                delDir("$directory/$file") :
                unlink("$directory/$file");
        }
    }
    if (readdir($handle) == false) {
        closedir($handle);
        rmdir($directory);
    }
}


/**
 * @param $directory
 * @return bool
 * @des 删除目录下面的所有文件，但不删除目录
 */
function del($directory) {
    if (is_dir($directory) == false) {
        $error = "该目录是不存在！";
        return false;
    }
    $handle = opendir($directory);
    while (($file = readdir($handle)) !== false) {
        if ($file != "." && $file != ".." && is_file("$directory/$file")) {
            unlink("$directory/$file");
        }
    }
    closedir($handle);
}


/**
 * URL组装 支持不同URL模式
 * @param string $url URL表达式，格式：'[模块/控制器/操作#锚点@域名]?参数1=值1&参数2=值2...'
 * @param string|array $vars 传入的参数，支持数组和字符串
 * @param string $suffix 伪静态后缀，默认为true表示获取配置值
 * @param boolean $domain 是否显示域名
 * @return string
 */
function url($url='',$vars='',$suffix=true,$domain=false) {
    $routes=install_get_routes();
    if(empty($routes)){
        return U($url,$vars,$suffix,$domain);
    }
    $routesKey = array_keys($routes);
    if(!in_array($url,$routesKey) || C('URL_MODEL') == 0){
        return U($url,$vars,$suffix,$domain);
    }

    // 解析URL
    $info   =  parse_url($url);
    $url    =  !empty($info['path'])?$info['path']:ACTION_NAME;
    if(isset($info['fragment'])) { // 解析锚点
        $anchor =   $info['fragment'];
        if(false !== strpos($anchor,'?')) { // 解析参数
            list($anchor,$info['query']) = explode('?',$anchor,2);
        }
        if(false !== strpos($anchor,'@')) { // 解析域名
            list($anchor,$host)    =   explode('@',$anchor, 2);
        }
    }elseif(false !== strpos($url,'@')) { // 解析域名
        list($url,$host)    =   explode('@',$info['path'], 2);
    }
    // 解析子域名
    if(isset($host)) {
        $domain = $host.(strpos($host,'.')?'':strstr($_SERVER['HTTP_HOST'],'.'));
    }elseif($domain===true){
        $domain = $_SERVER['HTTP_HOST'];
        if(C('APP_SUB_DOMAIN_DEPLOY') ) { // 开启子域名部署
            $domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.');
            // '子域名'=>array('模块[/控制器]');
            foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) {
                $rule   =   is_array($rule)?$rule[0]:$rule;
                if(false === strpos($key,'*') && 0=== strpos($url,$rule)) {
                    $domain = $key.strstr($domain,'.'); // 生成对应子域名
                    $url    =  substr_replace($url,'',0,strlen($rule));
                    break;
                }
            }
        }
    }

    // 解析参数
    if(is_string($vars)) { // aaa=1&bbb=2 转换成数组
        parse_str($vars,$vars);
    }elseif(!is_array($vars)){
        $vars = array();
    }
    if(isset($info['query'])) { // 解析地址里面参数 合并到vars
        parse_str($info['query'],$params);
        $vars = array_merge($params,$vars);
    }
    //参数解析网址替换
    $url = $routes[$url];
    if($vars){
        foreach($vars as $k => $v){
            $url = str_replace('[:' . $k .']', C('URL_PATHINFO_DEPR') . $v,$url);
        }
    }
        $url = preg_replace("/\[.*\]/",'',$url);
        $url = str_replace(array('/-'),array('/'),$url);

    if(C('URL_MODEL') == 0 ){
        $suffix = '';
    }
    if($suffix){

        $suf = preg_replace('/.*\//','',$url);

        if($suf){
            $url .= $suffix;
        }
    }else{
        $url .= ".html";
    }

    if($domain) {
        $url   =  (is_ssl()?'https://':'http://').$domain.$url;
    }
    return $url;
}

/**
 * URL组装 支持不同URL模式
 * @param string $url URL表达式，格式：'[模块/控制器/操作#锚点@域名]?参数1=值1&参数2=值2...'
 * @param string|array $vars 传入的参数，支持数组和字符串
 * @param string $suffix 伪静态后缀，默认为true表示获取配置值
 * @param boolean $domain 是否显示域名
 * @return string
 */
function UU($url='',$vars='',$suffix='.html',$domain=true){
    return url($url,$vars,$suffix,$domain);
}

function install_get_routes($refresh=false){
    $routes=F("routes");

    if( (!empty($routes)||is_array($routes)) && !$refresh){
        return $routes;
    }
    $routes=M("Route")->where("status=1")->order("listorder asc")->select();
    $routes = array_column($routes,'url','full_url');
    F("routes",$routes);
    $route_dir=SITE_PATH."/data/conf/";
    if(!file_exists($route_dir)){
        mkdir($route_dir);
    }
    $route_file=$route_dir."route.php";
    file_put_contents($route_file, "<?php\treturn " . stripslashes(var_export($routes, true)) . ";");
    return $routes;
}

function P($val){
    return dump($val);
}


function PageShow($count,$url,$limit = null){
    $limit = $limit == null ? C('DEFALUT_PAGE_SIZE') : $limit;
    $Page = new \Org\Util\Page($count,$limit);
    $Page->setConfig('header','<div class="pageNum">第%NOW_PAGE%/%TOTAL_PAGE%页</div>');
    $Page->setConfig('prev','上一页');
    $Page->setConfig('next','下一页');
    $Page->setConfig('last','末页');
    $Page->setConfig('first','首页');
    $Page->setConfig('theme','<div class="page">%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%</div>');
    $show = $Page->newShow($url);// 分页显示输出
    return $show;
}

function install_get_host(){
    $host=$_SERVER["HTTP_HOST"];
    $protocol=is_ssl()?"https://":"http://";
    return $protocol.$host;
}

/**
 * 随机字符串生成
 * @param int $len 生成的字符串长度
 * @return string
 */
function install_random_string($len = 6) {
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    );
    $charsLen = count($chars) - 1;
    shuffle($chars);    // 将数组打乱
    $output = "";
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}

function getWeatherIndex($type){
    $weatherIndex =array(
        'drsg'  => '穿衣指数',
        'uv'    => '紫外指数',
        'cw'    => '洗车指数',
        'trav'  =>  '旅游指数',
        'flu'   => 	'感冒指数',
        'sport' => 	'运动指数',
    );

    if(isset($weatherIndex[$type])){
        return $weatherIndex[$type];
    }else{
        return '生活指数';
    }


}